package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.utils.RegexUtils;
import com.leyou.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    private final String KEY_PREFIX="ly-user-verify";

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    public UserServiceImpl(StringRedisTemplate redisTemplate, AmqpTemplate amqpTemplate) {
        this.redisTemplate = redisTemplate;
        this.amqpTemplate = amqpTemplate;
    }

    @Override
    public Boolean exists(String data, Integer type) {
        String name=null;
        if (type==1){
            name="username";
            if(StringUtils.isEmpty(data)){
                throw new LyException(400,"用户明错误");
            }
        }
        if (type==2){
            name="phone";
            if(!RegexUtils.isPhone(data)){
                throw new LyException(400,"手机号错误");
            }
        }
        return this.query().eq(name,data).count()==1;


    }

    @Override
    public UserDTO queryUserByusernameAndPassword(String username, String password) {
        // 1.根据用户名查询
        User user = query().eq("username",username).one();

        // 2.判断是否存在
        if (user==null){
            throw new LyException(400,"用户不存在或用户名错误");
        }
        // 3.校验密码
//        if (!password.equals("heima114")){
//            throw new LyException(400,"密码输入错误");
//        }
        if (!passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(400,"密码输入错误");
        }
        // 4.转换DTO
        return new UserDTO(user);
    }

    @Override
    public void sendCode(String phone) {
        if (!RegexUtils.isPhone(phone)){
            throw new LyException(400,"手机号错误");
        }
        String code = RandomStringUtils.randomNumeric(6);
        Map<String,String>msg=new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);
        String key=KEY_PREFIX+phone;
        this.redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
    }

    @Override
    @Transactional
    public void register(User user, String code) {
        String key=KEY_PREFIX+user.getPhone();
        //验证码为空或错误
        if (StringUtils.isEmpty(code)||!code.equals(redisTemplate.opsForValue().get(key))){
            throw new LyException(400,"验证码错误");
        }

        //User user = user.toEntity(User.class);
        //密码加密，生成随机盐值
        String encodePassword=passwordEncoder.encode(user.getPassword());
        //根据算法，推测密文盐值，拿着盐值对密码加密
        //passwordEncoder.matches("heima114",encodePassword);
        user.setPassword(encodePassword);
        this.save(user);
    }
}
